package model.objects;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.mxgraph.model.mxCell;

public class RelationObject extends ModelingObject {

	private static final long serialVersionUID = 7613256124624897109L;

	private List<ModelingObject> relatedObjects = new ArrayList<ModelingObject>();

	private final int NUMBER_OF_ATTRIBUTES = 0;

	public RelationObject() {
		super("");
	}

	public RelationObject(String name) {
		super(name);
	}

	public RelationObject(String name, Object parentObject) {
		super(name);
		addParentObject(parentObject);
	}

	public void addRelatedObject(ModelingObject object) {
		relatedObjects.add(object);
	}

	public void removeRelatedObject(ModelingObject object) {
		relatedObjects.remove(object);
	}

	public Iterator<ModelingObject> getRelatedObjectsIterator() {
		return relatedObjects.iterator();
	}

	public List<ModelingObject> getRelatedObjects() {
		return relatedObjects;
	}

	public int attributesCount() {
		return super.attributesCount() + NUMBER_OF_ATTRIBUTES;
	}

	public void getAttributes(int types[], String names[], String values[], boolean enabled[]) {
		super.getAttributes(types, names, values, enabled);
	}

	public int windowHeight() {
		return super.windowHeight();
	}

	public void removeReferencesFromParents() {
		Iterator<Object> iterator = getParentObjects().iterator();
		while (iterator.hasNext()) {
			Object parent = iterator.next();
			if (parent != null) {
				if (((mxCell)parent).getValue() instanceof EntityObject) {
					EntityObject entityObject = (EntityObject) ((mxCell)parent).getValue();
					entityObject.removeChildObject(this);
					entityObject.setSelfRelated(false);

				} else if (((mxCell)parent).getValue() instanceof AssociativeEntityObject) {
					AssociativeEntityObject entityObject = (AssociativeEntityObject) ((mxCell)parent).getValue();
					entityObject.removeChildObject(this);
					entityObject.setSelfRelated(false);

				}
			}
		}
	}

	public String getStyle() {
		return "relation";
	}

	public ConnectorObject getConnectorObject(mxCell relationCell, EntityObject entityObject) {
		ConnectorObject returnedObject = null;

		int count = relationCell.getEdgeCount();
		for (int i = 0; i < count; i++) {
			mxCell edge = (mxCell) relationCell.getEdgeAt(i);
			if (edge.getValue() instanceof ConnectorObject) {
				if ((edge.getSource() == relationCell && ((mxCell)edge.getTarget()).getValue() instanceof EntityObject &&
						(EntityObject)((mxCell)edge.getTarget()).getValue() == entityObject) ||
						(edge.getTarget() == relationCell && ((mxCell)edge.getSource()).getValue() instanceof EntityObject &&
						(EntityObject)((mxCell)edge.getSource()).getValue() == entityObject))
					returnedObject = (ConnectorObject)edge.getValue();						

			}
		}

		return returnedObject;
	}
}
